package com.dbq.fast.business.login.api;

import android.os.Build;
import android.text.TextUtils;

import com.dbq.fast.App;
import com.dbq.fast.BuildConfig;
import com.dbq.fast.R;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.util.SystemUtil;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import java.util.HashMap;

import okhttp3.RequestBody;

/**
 * Created by yuanchen on 2018/5/23.
 */

public class NewLoginApi {

    private static HttpManager httpManager = HttpManager.getInstance();

    public static void accessVerifiCode(String phone, RemoteApiCallBack<String> c){
        httpManager.getHttpService()
                .requestVerifiCode(phone)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("");
                    }else {
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1, "");
                });
    }

    public static void accessPwdVerifiCode(String phone, RemoteApiCallBack<String> c){
        httpManager.getHttpService()
                .requestPwdVerifiCode(phone)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("");
                    }else {
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1, "");
                });
    }

    public static void checkVerifiCode(String phone, String verifiCode, RemoteApiCallBack<String> c){
        HashMap hashMap = new HashMap();
        hashMap.put("account", phone);
        hashMap.put("captcha", verifiCode);
        httpManager.getHttpService()
                .checkVerifiCode(hashMap)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("");
                    }else {
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1, "");
                });
    }

    public static void register(String phone, String pwd, String verifiCode, RemoteApiCallBack<CustomProfile> c){
        CustomProfile profile = generate(phone, pwd);
        profile.setCaptcha(verifiCode);
        String bodyStr = GsonT.toJson(profile);
        RequestBody body = httpManager.getPostBody(bodyStr);
        httpManager.getHttpService()
                .register(111, profile.getParentId(), body)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        CustomProfile temp = result.getData();
                        profile.setToken(temp.getToken());
                        profile.setAccount(temp.getAccount());
                        profile.setUserServiceLevel(temp.getUserServiceLevel());
                        profile.setNewTestService(temp.getNewTestService());
                        profile.setVpnId(temp.getVpnId());
                        profile.setRefreshToken(temp.getRefreshToken());
                        profile.setExpiresIn(temp.getExpiresIn());
                        profile.setNewUserDiscount(temp.getNewUserDiscount());
                        c.onSuccess(profile);
                    }else {
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                });
    }

    public static void login(String account, String pwd, RemoteApiCallBack<CustomProfile> c){
        CustomProfile profile = generate(account, pwd);
        String bodyStr = GsonT.toJson(profile);
        RequestBody body = httpManager.getPostBody(bodyStr);
        httpManager.getHttpService()
                .login(111, profile.getParentId(), body)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        CustomProfile temp = result.getData();
                        profile.setToken(temp.getToken());
                        profile.setAccount(temp.getAccount());
                        profile.setUserServiceLevel(temp.getUserServiceLevel());
                        profile.setNewTestService(temp.getNewTestService());
                        profile.setVpnId(temp.getVpnId());
                        profile.setRefreshToken(temp.getRefreshToken());
                        profile.setExpiresIn(temp.getExpiresIn());
                        profile.setNewUserDiscount(temp.getNewUserDiscount());
                        profile.setEmail(temp.getEmail());
                        c.onSuccess(profile);
                    }else{
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                });
    }

    public static void resetPwd(String phone, String pwd, String verifiCode, RemoteApiCallBack<String> c){
        HashMap hashMap = new HashMap();
        hashMap.put("account", phone);
        hashMap.put("pwd", pwd);
        hashMap.put("pwdVerify", pwd);
        hashMap.put("captcha", verifiCode);
        httpManager.getHttpService()
                .resetPwd(hashMap)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("");
                    }else {
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                });
    }

    public static void logOut(RemoteApiCallBack<String> c){
        String token = User.getInstance().getToken();
        if (TextUtils.isEmpty(token)) return;
        httpManager.getHttpService()
                .newLogOut(token)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if(result.isSuccess()){
                        c.onSuccess("");
                    }else if(result.getCode() == 401){
                       new Thread(()->{
                           String newToken = LoginApi.refreshTokenSync(true);
                           if ("".equals(newToken)) return;
                           logOut(c);
                       }).start();

                    }else {
                        c.onFail(result.getCode(), result.getMsg());
                    }
                }, throwable -> {
                    c.onSuccess("");
                    RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_LOGOUT);
                });
    }

    public static CustomProfile generate(String phone, String pwd) {
        CustomProfile profile = new CustomProfile();
        profile.setAccount(phone);
        profile.setPwd(pwd);
        profile.setPwdVerify(pwd);
        profile.setLoginChannel(4);
        profile.setPlatformId(SystemUtil.getAndroidId(App.getContext()));
        profile.setUuid(SystemUtil.getAndroidId(App.getContext()));
        profile.setSex("3");
        profile.setCountry(SystemUtil.getCountry(App.getContext()));
        profile.setParentId(User.getInstance().getParentId());
        profile.setOsVer(Build.VERSION.RELEASE);
        profile.setAppVer(BuildConfig.VERSION_NAME);
        return profile;
    }

}
